package org.mv.mm.docs;

//Don't optimalize imports via NetBeans 7.1 IDE feature
import org.mv.mm.common.CentralLookup;
import org.mv.mm.api.data.IDataProvider;
import java.io.IOException;
import java.util.Collection;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.mv.mm.api.Doc;
import org.mv.mm.api.Fragment;
import org.mv.mm.api.capabilities.ICreatableFragmentCapability;
import org.mv.mm.api.capabilities.IReloadableFragmentCapability;
import org.mv.mm.api.capabilities.IRefreshableFragmentViewCapability;
import org.openide.DialogDisplayer;
import org.openide.NotifyDescriptor;
import org.openide.nodes.Node;
import org.openide.util.NbBundle.Messages;
import org.openide.util.datatransfer.NewType;
import static org.mv.mm.docs.Bundle.*;

/**
 *
 * @author Martin
 */
@Messages({
  "LBL_NewFragmentWorkName_dialog=Fragment working title*:",
  "LBL_NewFragmentWorkNameError_dialog=Please, try another working title for the new fragment:",
  "TITLE_NewFragment_dialog=New fragment"})
public class FragmentNewType extends NewType {

  private final IDataProvider dataProvider;
  private final Doc doc;
  private final Node node;
  private final boolean root;
  private static final Logger logger = Logger.getLogger(FragmentNewType.class.getName());

  public FragmentNewType(IDataProvider dataProvider, Node node, Doc document, boolean root) {
    this.dataProvider = dataProvider;
    this.node = node;
    this.root = root;
    this.doc = document;
  }

  @Override
  public String getName() {
    return LBL_NewFragmentWorkName_dialog();
  }

  @Override
  public void create() throws IOException {
    // Use dialog for name of new Fragment
    Object result;
    String fragWorkName;
    NotifyDescriptor.InputLine msg = new NotifyDescriptor.InputLine(LBL_NewFragmentWorkName_dialog(), TITLE_NewFragment_dialog());

    result = DialogDisplayer.getDefault().notify(msg);
    fragWorkName = msg.getInputText();

    // Now if there is not any user input, it repeats the dialog.
    while (NotifyDescriptor.YES_OPTION.equals(result) && fragWorkName.equals("")) {
      result = DialogDisplayer.getDefault().notify(msg);
      fragWorkName = msg.getInputText();
    }
    if (!NotifyDescriptor.YES_OPTION.equals(result)) {
      return;
    }

    try {
      Fragment frag = null;
      boolean firstTry = true;
      // Repeat, until user inputs unique workName
      while (frag == null) {
        if (!firstTry) {
          // Set a different message
          msg = new NotifyDescriptor.InputLine(LBL_NewFragmentWorkNameError_dialog(), TITLE_NewFragment_dialog());
          msg.setInputText(fragWorkName);

          result = DialogDisplayer.getDefault().notify(msg);
          if (NotifyDescriptor.YES_OPTION.equals(result)) {
            fragWorkName = msg.getInputText();
            // Repeat if the user inputs empty string
            while (fragWorkName.equals("")) {
              result = DialogDisplayer.getDefault().notify(msg);
              if (!NotifyDescriptor.YES_OPTION.equals(result)) {
                return;
              } else {
                fragWorkName = msg.getInputText();
              }
            }
          } else {
            return;
          }

        } else {
          firstTry = false;
        }

        //Pass the new data to the dataProvider's implementation of the create capability
        // and get new Fragment, or null if the id field (workName) is not unique
        frag = createNew(dataProvider.getLookup().lookup(ICreatableFragmentCapability.class), fragWorkName);
      }

      doc.addFragment(frag);
      notifyRefreshable(frag);
      
    } catch (Exception ex) {
      logger.log(Level.SEVERE, null, ex); //TODO provide a message from Bundle
    }
  }

  private Fragment createNew(ICreatableFragmentCapability cec, String fragWorkName) throws Exception {
    if (!root) {
      Fragment parent = node.getLookup().lookup(Fragment.class);
      //Create a new Fragment object:
      return cec.create(doc, fragWorkName, parent);
    } else {
      return cec.create(doc, fragWorkName, null);
    }
  }

  private void notifyRefreshable(Fragment frag) throws Exception {
    //Refresh the list of fragments via the implementation of the reload capability: 
    IReloadableFragmentCapability r = dataProvider.getLookup().lookup(IReloadableFragmentCapability.class);
    r.reload();

    /*
     * IRefreshableFragmentViewCapability rvc; rvc =
     * node.getLookup().lookup(IRefreshableFragmentViewCapability.class);
     * rvc.refreshChildren();
     */
    //Previous commented code was instead of this next. It was for updating only one node, not all nodes (in all opened windows)
    CentralLookup cl = CentralLookup.getDefault();
    Collection<? extends IRefreshableFragmentViewCapability> nodes = cl.lookupAll(IRefreshableFragmentViewCapability.class);
    for (IRefreshableFragmentViewCapability rvc : nodes) {
      rvc.refreshAfterNew(frag.getParentFragment());
    }
  }
}
